<?php
namespace App\Utils\Other\Safepay\Refund;

use App\Exception\InternalException;
use App\Utils\Other\Safepay\App;
use Hyperf\Collection\Arr;
use function Hyperf\Config\config;

Class Mini extends App {

    public function __construct()
    {
        parent::__construct();
        $this->setConfig(['notify' => getDomain()."/publics/v1/refund/notify/safepayMini"]);
        $this->setConfig(['appid' => config('cloud.mini.app_id')]);

    }

    /**
     * 付款
     * @param array $params
     * @return array [$request, $response, $params]
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function handle(array $params):array
    {
        $data = [
            'orderCode' => $params['refund_no'],
            'originalSourceTrace' => $params['pay_order_no'],
            'refundReason' => $params['remark'],
            'tradeamt' => $params['refund_amount']
        ];
        $params = $this->getParams($data);
        $this->setPath('refund');
        return $this->request($params);
    }

    /**
     * 获取参数
     * @param array $params
     * @return array
     */
    protected function getParams(array $params)
    {
        $params = parent::getParams($params); // TODO: Change the autogenerated stub
        $params['notify'] = $this->getConfig('notify');
        $params['businessType'] = 'zwrefund';

        return $params;
    }

    /**
     * 响应
     * @param $response
     * @param array $params
     * @return array
     */
    protected function response($response, array $params=[]):array
    {
        if (!isset($response['code']) || ($response['code'] != 0)) {
            $message = Arr::get($response, 'message');
            if (!$message) {
                throw new InternalException('response is null');
            }
            $messageJson = json_decode($message, true);
            if (false === $messageJson || !Arr::has($messageJson, 'message')) {
                throw new InternalException($message);
            }
            throw new InternalException($messageJson['message']);
        }

        $body = Arr::get($response['data']);

        return [
            $params,
            $response,
            $body
        ];
    }
}